
var mdk = require('./md55.js');
var HOST = "http://shsandbox.etonepay.com/kmzgw";
// var HOST = "https://gws.bitbonds.cn";
var md5key = ""

//查询商户列表
var INDEX = HOST + "/mini_program/getBusiProduct"; //获取商圈首页商品列表
var QUAN = HOST + "/mini_program/getBusiAllProduct"; //获取商圈全部商品列表

var SHOPDETAIL = HOST + "/mini_program/getProductDetail";//商品详情

var SHOPSHOW = HOST + "/mini_program/getShopProduct" //门店首页
var GOODALL = HOST +"/mini_program/getShopAllProduct" //门店所有
var INTERCAR = HOST +"/mini_program/updateShopCar"//更新购物车
var QUERYGOODS = HOST + "/mini_program/queryShopCar" //查询购物车
var GETAID = HOST + "/mini_program/getSessionKey";//获取appid
var LOGIN = HOST +"/mini_program/login"  //登陆
var GETPHONECODE = HOST + "/mini_program/getVerificationCode"  //获取手机验证码
var ENTERGROUP = HOST +"/mini_program/registerPhone" //加入会员
var EARAGROUP = HOST +"/mini_program/getAreaData" //获取省市区
var STOREADDRESS = HOST +"/mini_program/saveMemAddress" //保存地址
var USERLOCATION = HOST +"/mini_program/getMemberAddress"  //查询会员地址
var SUPPORTCARTS = HOST +"/mini_program/placeOrder"  //提交订单
var CHECKLIST = HOST +"/mini_program/getMemberProductOrder" //查找订单
var UPDATELOCA = HOST +"/mini_program/updateMemAddress" //修改会员地址
var CARDREQURE = HOST +"/mini_program/showUserCardList"  //查询卡
var COUPONCHECK = HOST +"/mini_program/showUserCouponList" //查询券
var CARDDETAIL = HOST +"/mini_program/queryCardDetail" //会员卡详情
var IMINDATASETE = HOST + "/mini_program/immediateSettle"  //查询商户码、会员卡券
var WXPAYCODE = HOST +"/mini_program/wxPay"  //查询paycode

var UNITCODE = 'unitCode';

var SelectedBankInfo = 'SelectedBankInfo';
var LOGINSUCCESS = 'loginsuccess';


//get请求
function Cpic_fetchGet(url, callback) {
  wx.request({
    url: url,
    header: { 'Content-type': 'application/json' },
    success(res) {
      callback(null, res.data)
    },
    fail(e) {
      console.log(e)
      callback(e)
    }
  })
}

function NCpic_fetchPost(url, jsonParm,njsonParm, callback){
  var tempstr = '';
  var dic = jsonParm;
  var sdic = Object.keys(dic).sort();
  for (var ki in sdic) {
    if(sdic[ki] == njsonParm ){
      continue;
    }
    console.log(sdic[ki] + ":" + dic[sdic[ki]] + ",");
    tempstr += sdic[ki] + "=" + dic[sdic[ki]];
  }
  tempstr += md5key;
  tempstr = tempstr.replace(/\s+/g, "");
  var password = mdk.hexMD5(tempstr);
  password = password.toUpperCase()
  console.log("mdk:" + password);
  jsonParm["Md5Sign"] = password;
  console.log('发送post请求 url=' + url + '|' + 'jsonParm=' + JSON.stringify(jsonParm));
  // jsonParm.channel = "zzckapplet";

  wx.request({
    method: 'post',
    url: url,
    header: { 'Content-type': 'application/x-www-form-urlencoded' },
    data: JSON.stringify(jsonParm),
    success(res) {
      // wx.hideToast();
      var response_code = res.data.ReturnCode;
      var response_msg = res.data.ReturnMsg;
      //下面的showtoast 有问题 show 不出来
      if (response_msg === "" || response_code === "") {
        wx.showToast({
          title: "网络请求异常",
          icon: 'loading',
          mask: true,
          duration: 3000
        })
      } else if (response_code !== "00") {
        wx.showToast({
          title: response_msg.toString(),
          icon: 'loading',
          mask: true,
          duration: 3000
        })
        callback(response_code, res.data);
      } else {
        callback(response_code, res.data);
      }

      // console.log('接口地址=' + url + "返回为=" + JSON.stringify(res.data))
    },
    fail(e) {
      wx.hideToast();
      console.log(e)
      callback(e)
    },
    complete: function () {
      // complete
      wx.hideToast();
    }
  })
}
//post请求
function Cpic_fetchPost(url, jsonParm, callback) {
  var tempstr = '';
  var dic = jsonParm;
  var sdic = Object.keys(dic).sort();
  for (var ki in sdic) {
    console.log(sdic[ki] + ":" + dic[sdic[ki]] + ",");
    tempstr += sdic[ki] + "=" + dic[sdic[ki]];
  }
  tempstr += md5key;
  tempstr = tempstr.replace(/\s+/g, ""); 
  var password = mdk.hexMD5(tempstr);
  password = password.toUpperCase()
  console.log("mdk:" + password);
  jsonParm["Md5Sign"] = password;
  console.log('发送post请求 url=' + url + '|' + 'jsonParm=' + JSON.stringify(jsonParm));
  // jsonParm.channel = "zzckapplet";
  
  wx.request({
    method: 'post',
    url: url,
    header: { 'Content-type': 'application/x-www-form-urlencoded' },
    data: JSON.stringify(jsonParm),
    success(res) {
      // wx.hideToast();
      var response_code = res.data.ReturnCode;
      var response_msg = res.data.ReturnMsg;
      //下面的showtoast 有问题 show 不出来
      if (response_msg === "" || response_code === "") {
        wx.showToast({
          title: "网络请求异常",
          icon: 'loading',
          mask: true,
          duration: 3000
        })
      }else if(response_code !=="00"){
        wx.showToast({
          title: response_msg.toString(),
          icon: 'loading',
          mask: true,
          duration: 3000
        })
        callback(response_code, res.data);
      }else {
        callback(response_code, res.data);
      }
    },
    fail(e) {
      wx.hideToast();
      console.log(e)
      callback(e)
    },
    complete: function () {
    	// complete
    	wx.hideToast();
    }
  })
}


//上传图片请求
function Cpic_FetchPicturePost(url, file, formData, name, callback) {
  formData.channel = "zzckapplet";
  console.log('上传图片请求 url=' + url + 'formData=' + JSON.stringify(formData) + '图片名字=' + name);
  wx.uploadFile({
    url: url,
    filePath: file,
    formData: formData,
    name: name,
    success: function (res) {
      var data = res.data
      var status = res.statusCode
      console.log("success_data", data);
      console.log("success_status", status);
      console.log("==上传图片请求返回成功==" + res);
      callback(res.data);
    },
    complete: function () {
      console.log("upload complete");
    },
    fail: function (res) {
      console.log("==上传图片请求失败==", res);
    }
  })
}

//写入数据存储
function SetCpic_localStorage(storage_key, storage_data) {
  try {
    wx.setStorageSync(storage_key, storage_data);
    console.log("存储成功" + storage_key + "===" + storage_data)
  } catch (e) {
  }
}

//读取存储数据
function getCpic_localStorage(storage_key, callback) {
  try {
    var value = wx.getStorageSync(storage_key);
    if (value) {
      callback(value);
    }
  } catch (e) {
    // Do something when catch error
    console.log(e);
  }
}

//清除数据存储
function ClearCpic_localStorage() {
  wx.clearStorage();
}

//移除数据存储
function RemoveCpic_localStorage(storage_key) {
  wx.removeStorage({
    key: storage_key
  })
}

function CheckLoginStatus(callback) {
  getCpic_localStorage(LOGINSUCCESS, function (res) {
    if (res !== '1') {
      wx.redirectTo({
        url: '../login/login',
      })
    }
    else {
      callback();
    }
  });
}

//存储log  url--当前页面  content--日志内容
function SaveLogs(url, content) {
  var caseNo = "";
  this.getCpic_localStorage(this.LOCALCASENO, function (res) {
    caseNo = res;
  });
  this.Cpic_fetchPost(this.WEBLOGS, { "url": url, "type": "0", "content": content, "caseNo": caseNo }, (err, res) => {
    console.log("存储日志成功" + res);
  })
}

//支付签名
function PaypackSign(jsonParm, callback) {
  var tempstr = '';
  var dic = jsonParm;
  var sdic = Object.keys(dic).sort();
  for (var ki in sdic) {
    console.log(sdic[ki] + ":" + dic[sdic[ki]] + ",");
    tempstr += sdic[ki] + "=" + dic[sdic[ki]];
  }
  tempstr = tempstr.replace(/\s+/g, "");
  var password = mdk.hexMD5(tempstr);
  password = password.toUpperCase();
  callback(password);
  // return password;
}

module.exports = {
  INDEX: INDEX,
  Cpic_fetchPost: Cpic_fetchPost,
  NCpic_fetchPost: NCpic_fetchPost,
  PaypackSign: PaypackSign,
  QUAN: QUAN,
  SHOPDETAIL:SHOPDETAIL,
  SHOPSHOW: SHOPSHOW,
  GOODALL: GOODALL,
  INTERCAR: INTERCAR,
  QUERYGOODS: QUERYGOODS,
  GETAID: GETAID,
  LOGIN: LOGIN,
  GETPHONECODE: GETPHONECODE,
  ENTERGROUP: ENTERGROUP,
  EARAGROUP: EARAGROUP,
  STOREADDRESS: STOREADDRESS,
  USERLOCATION: USERLOCATION,
  SUPPORTCARTS: SUPPORTCARTS,
  CHECKLIST: CHECKLIST,
  UPDATELOCA: UPDATELOCA,
  CARDREQURE: CARDREQURE,
  COUPONCHECK: COUPONCHECK,
  CARDDETAIL: CARDDETAIL, 
  IMINDATASETE: IMINDATASETE,
  WXPAYCODE: WXPAYCODE,
}
